package com.hyjx.framework.uc.role;

import com.hyjx.framework.common.CommonUtil;
import com.hyjx.framework.common.tree.TreeObject;
import com.hyjx.framework.common.util.StringHelper;
import com.hyjx.framework.orm.dao.IBaseDao;
import com.hyjx.framework.orm.dao.Pager;
import com.hyjx.framework.service.RightManager;
import com.hyjx.framework.service.UserCenterService;
import com.hyjx.framework.service.model.CacheOrg;
import com.hyjx.framework.service.model.CacheRole;
import com.hyjx.framework.uc.depart.DepartModel;
import com.hyjx.framework.uc.user.UserInfo;
import com.hyjx.framework.uc.user.UserModel;
import com.hyjx.framework.uc.user.UserRoleModel;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 角色服务 实现类
 */
@Service
@Transactional
public class RoleServiceImpl implements RoleService {
    @Resource
    private IBaseDao dao;

    @Override
    @SuppressWarnings("unchecked")
    public String queryList(RoleModel model) {
        if ("1".equals(UserCenterService.getCurrentUserInfo().getUserIsAdmin())) {
            model.setLevelId("001");
            model.setParentOrgCodes("");
        } else {
            try {
                String levelId = RightManager.getSysOrgs().get(UserCenterService.getCurrentUserInfo().getDataOrgCode()).getOrg().getLevelid();
                model.setLevelId(levelId);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            String allSuperCodes = RightManager.getOrgAllSuperCodes(model.getOrg_code());
            if (!"".equals(allSuperCodes)) {
                model.setParentOrgCodes(" or org_code in (" + allSuperCodes + ") ");
            }
        }

        Pager pager = dao.getPager(model.getModuleName() + ".queryList", model.getModuleName() + ".queryCount", model);
        List<RoleModel> rolelist = pager.getResultList();
        for (RoleModel r : rolelist) {
            DepartModel dm = RightManager.getOrgByCode(r.getOrg_code());
            if (dm != null) {
                r.setOrg_name(dm.getDepart_name());
                if (r.getOrg_code().equals(UserCenterService.getCurrentUserInfo().getDataOrgCode())) {
                    r.setEditAble("1");
                }
            }
        }
        pager.setResultList(rolelist);
        return CommonUtil.getPageJsonStr(pager);
    }

    @SuppressWarnings({"unchecked", "unused"})
    private List<RoleModel> getRoleByDepartCode(String depart_code) {
        return dao.queryObjectList(new RoleModel().getModuleName() + ".getRoleByDepartCode", depart_code);
    }

    @Override
    public boolean add(RoleModel model) {
        model.setOrg_code(UserCenterService.getCurrentUserInfo().getDataOrgCode());
        model.setDepart_code(UserCenterService.getCurrentUserDepartCode());
        model.setCreate_user_id(UserCenterService.getCurrentUserId());

        model.setCreate_time(StringHelper.getDateTime());
        dao.addObject(model.getModuleName() + ".insert", model);

        if ("1".equals(model.getRole_type())) {
            saveRelation(model.getRole_id(), "1", model.getMenuCodes());
        } else {
            saveRelation(model.getRole_id(), "2", model.getOrgCodes());
        }
        return true;
    }

    @Override
    public RoleModel getInfoById(String s) {
        RoleModel model = null;
        model = (RoleModel) dao.queryObject(new RoleModel().getModuleName() + ".getInfoById", s);
        return model;
    }

    @Override
    public int edit(RoleModel model) {
        dao.deleteObject(model.getModuleName() + ".deleteRoleMenu", model.getRole_id());
        dao.deleteObject(model.getModuleName() + ".deleteRoleDepart", model.getRole_id());

        dao.updateObject(model.getModuleName() + ".update", model);
        if ("1".equals(model.getRole_type())) {
            saveRelation(model.getRole_id(), "1", model.getMenuCodes());
        } else {
            saveRelation(model.getRole_id(), "2", model.getOrgCodes());
        }
        return 1;
    }


    /**
     * 保存角色对应关系（菜单、操作、单位）
     *
     * @param roleId    角色id
     * @param roleType  对应菜单编码
     * @param relaCodes 对应单位编码
     */
    private void saveRelation(String roleId, String roleType, String relaCodes) {
        if ("1".equals(roleType)) {
            String funcCodes = relaCodes;
            //角色对应菜单(包含子系统id,菜单code,操作id)
            if (funcCodes != null && !"".equals(funcCodes)) {
                String[] id = funcCodes.split(",");
                List<RoleMenuModel> list = new ArrayList<RoleMenuModel>();
                for (int i = 0; i < id.length; i++) {
                    String menuId = id[i];
                    if (menuId != null && !"".equals(menuId)) {
                        RoleMenuModel rm = new RoleMenuModel();
                        String menuType = menuId.substring(0, 1);
                        rm.setMenutype(menuType);
                        rm.setMenu_code(menuId.substring(1));
                        rm.setRole_id(roleId);
                        rm.setId(StringHelper.getPrimaryKey());
                        list.add(rm);
                    }
                }
                dao.batchUpdateObject(new RoleModel().getModuleName() + ".insertRoleMenu", list);
            }
        } else {
            //角色对应单位
            if (relaCodes != null && !"".equals(relaCodes)) {
                String[] ids = relaCodes.split(",");
                List<RoleOrgModel> list = new ArrayList<RoleOrgModel>();
                for (int i = 0; i < ids.length; i++) {
                    String id = ids[i];
                    if (id != null && !"".equals(id)) {
                        RoleOrgModel ro = new RoleOrgModel();
                        ro.setRole_id(roleId);
                        ro.setOrg_code(id);
                        ro.setId(StringHelper.getPrimaryKey());
                        list.add(ro);
                    }
                }
                dao.batchUpdateObject(new RoleModel().getModuleName() + ".insertRoleOrg", list);
            }
        }
    }

    @Override
    public int delete(String ids) {
        RoleModel model = new RoleModel();
        String[] id_array = ids.split(",");
        int num = 0;
        for (String id : id_array) {
            dao.deleteObject(model.getModuleName() + ".deleteRoleMenu", id);
            dao.deleteObject(model.getModuleName() + ".deleteRoleDepart", id);
            dao.deleteObject(model.getModuleName() + ".deleteRoleUser", id);
            dao.deleteObject(model.getModuleName() + ".delete", id);
            num++;
        }
        return num;
    }

    @SuppressWarnings("unchecked")
    @Override
    public String getRoleMenuStr(String roleId) {
        StringBuffer sb = new StringBuffer();

        List<RoleMenuModel> list1 = dao.queryObjectList(new RoleModel().getModuleName() + ".queryRoleMenuList", roleId);
        if (list1.size() > 0) {
            for (RoleMenuModel m : list1) {
                sb.append("," + m.getMenu_code());
            }
        } else {
            sb.append(",");
        }
        sb.append(",");

        return sb.toString();
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<TreeObject> getAll() {
        List<TreeObject> result = (List<TreeObject>) dao.queryObjectList(new RoleModel().getModuleName() + ".getAllMenu", "1");
        return result;
    }

    @SuppressWarnings("unchecked")
    @Override
    public String getRoleOrgStr(String roleId) {
        StringBuffer sb = new StringBuffer();
        List<RoleOrgModel> list = dao.queryObjectList(new RoleModel().getModuleName() + ".queryRoleOrgList", roleId);
        if (list.size() > 0) {
            for (RoleOrgModel m : list) {
                sb.append("," + m.getOrg_code());
            }
        } else {
            sb.append(",");
        }
        if (sb.charAt(0) == ',') {
            return sb.substring(1, sb.length());
        } else
            return sb.toString();
    }

    @Override
    public List<RoleModel> queryRoleListByOrgCode(String orgCode) {
        List<RoleModel> list = new ArrayList<RoleModel>();
        Map<String, CacheRole> map = RightManager.getSysRoles();
        DepartModel departByCode = RightManager.getDepartByCode(orgCode);
        String orgLevelId = null;
        if (departByCode != null) {
            orgLevelId = RightManager.getDepartByCode(orgCode).getLevelid();
        }
        if (orgLevelId == null)
            orgLevelId = "";
        Map<String, CacheOrg> cacheorgs = RightManager.getSysOrgs();
        for (CacheRole model : map.values()) {
            String roleOrgCode = model.getRole().getOrg_code();

            if (orgCode.equals(roleOrgCode)) {
                list.add(model.getRole());
            } else {
                if (roleOrgCode != null) {
                    if (cacheorgs.get(roleOrgCode) != null) {
                        String roleOrgLevelId = cacheorgs.get(roleOrgCode).getOrg().getLevelid();
                        if (roleOrgLevelId == null) {
                            roleOrgLevelId = "";
                        }
                        if (orgLevelId.startsWith(roleOrgLevelId)) {
                            list.add(model.getRole());
                        }
                    }
                }
            }
        }
        return list;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<RoleModel> queryAllRoles() {
        List<RoleModel> list = dao.queryObjectList(new RoleModel().getModuleName() + ".queryAllRole");
        return list;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<RoleOrgModel> queryAllRoleOrgList() {
        List<RoleOrgModel> list = dao.queryObjectList(new RoleModel().getModuleName() + ".queryAllRoleOrgList");
        return list;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<RoleMenuModel> queryAllRoleMenuList() {
        return dao.queryObjectList(new RoleModel().getModuleName() + ".queryAllRoleMenuList");
    }

    @Override
    public boolean disableRoleByDeptCode(String deptCode) {
        dao.updateObject(new RoleModel().getModuleName() + ".disableRoleByDeptCode", deptCode);
        return true;
    }

    @Override
    public boolean saveRoleUser(String roleId, String userIds) {
        List<UserRoleModel> list = new ArrayList<UserRoleModel>();
        String[] ids = userIds.split(",");
        for (int i = 0; i < ids.length; i++) {
            String userId = ids[i];
            if (userId != null && !"".equals(userId)) {
                UserRoleModel ur = new UserRoleModel();
                ur.setRole_id(roleId);
                ur.setUser_id(userId);
                ur.setId(StringHelper.getPrimaryKey());
                list.add(ur);
            }
        }

        dao.deleteObject(new RoleModel().getModuleName() + ".deleteRoleUser", roleId);
        dao.batchInsertObject(new UserModel().getModuleName() + ".insertUserRole", list);
        return true;
    }
}